/*
 测试类: PartRequirePlanControllerTest,ScheduledCargoGetNCDataControllerTest,SalesOrderControllerTest,StockDetailsWebserviceTest
*/
global class StockDetailsWebservice {

    private static Map<String ,String> getMapfromLabel(String lbl,Boolean isReverse ){
        Map<String ,String> tmp =  new Map<String ,String>();
        List<String>  tl = lbl.split(',');
        for (String cps  :tl ) {
            List<String> cpl = cps.split('-');
            if(isReverse){
                tmp.put(cpl[1], cpl[0]);
            }else{
                tmp.put(cpl[0], cpl[1]);
            }
        }
        return tmp;

    }
 
    //科研样品 推送到NC 为预订单
    WebService static String postGiftApplication(Id id ){

        List<GiftApplication__c> snList = [select Id, IsSycToNc__c,Destination__c ,Company__c,ApplyCustomer__r.AccountNumber,States__c from GiftApplication__c where Id=:id];
        GiftApplication__c sn = null;
        if(snList.size() > 0){
            sn = snList[0];
        }else{
            return '科研样品申请单Id错误!';
        }
        if(sn.States__c != '已批准')return '未审批的科研样品申请不能同步!';
        if(sn.Company__c == null)return '科研样品申请公司必填!';
        if(sn.IsSycToNc__c ==true ) return '已经同步,不要重复点击!';
        Map<String,String >salesMap = getMapfromLabel(Label.Vsalestrucode,true);
        Map<String,String >scomMap = getMapfromLabel(Label.ShortCompanyName,false);
        String companycode = ImportObject.getPicklistValues('Contract__c', 'Corpcode__c', false).get(sn.Company__c);
        String scode = salesMap.get(scomMap.get(companycode));
        if(scode == null) return '请联系系统管理员维护销售组织编码!'; 


        Map<String,String> headMap = new Map<String,String>();
        headMap.put('ccurrencytypeid','CNY');
        headMap.put('ccustomerid',sn.ApplyCustomer__r.AccountNumber);
        headMap.put('creceiptcorpid',sn.ApplyCustomer__r.AccountNumber);
        headMap.put('creceiptcustomerid',sn.ApplyCustomer__r.AccountNumber);
        headMap.put('coperatorid',sn.ApplyCustomer__r.AccountNumber);

        headMap.put('csalecorpid',scode);//销售组织编码
        //headMap.put('csalecorpid','01');
        headMap.put('vnote','科研样品申请');

        headMap.put('fstatus','1');
        headMap.put('creceipttype','38');
        headMap.put('nexchangeotobrate','1.0');
        headMap.put('pk_corp',companycode);//公司
        headMap.put('pk_defdoc6',sn.ApplyCustomer__r.AccountNumber);
        headMap.put('vdef6',sn.ApplyCustomer__r.AccountNumber+'-'+sn.ApplyCustomer__r.AccountNumber);
        headMap.put('vreceiveaddress', sn.Destination__c);
        headMap.put('dbilldate',Utils.date2string(Date.valueOf(System.now())));
        headMap.put('dabatedate',Utils.date2string(Date.valueOf(System.now().addMonths(2))));


        List<GiftApplicationDetails__c> sdList = [select Id,Product__c,Product__r.Unit__c,Product__r.NCCode__c,GiftApplication__c,Quantity__c,Remark__c
        from GiftApplicationDetails__c where GiftApplication__c =: id ];
        if(sdList.size() == 0)return '没有未同步的科研样品申请明细!';
        ///分单
        List<Map<String,String>> bodyList = new List<Map<String,String>>();
        Integer i = 0;
        for (GiftApplicationDetails__c sd: sdList) {
            i++;
            Map<String,String> body = new Map<String,String>();
            body.put('ccurrencytypeid','CNY' );
            body.put('crowno', String.valueOf(i));
            body.put( 'cinventoryid',sd.Product__r.NCCode__c);//存货编码
            body.put('cunitid',sd.Product__r.Unit__c);//单位
            body.put('ndiscountrate','100');
            body.put('pk_corp',companycode );//公司编码
            //body.put('nnumber', '2');
            body.put('vdef4', sd.GiftApplication__c);//主表pk
            body.put('vdef3', sd.Id);//子表pk 
            body.put('vdef5', 'SFKYYP');//子表pk 
          
            body.put('nnumber', String.valueOf(sd.Quantity__c));//数量


            //body.put('ntaxrate', '17');
            body.put('nmny', '0.01');
            body.put('nprice', '0.01');
            body.put('nnetprice', '0.01');
            body.put('frownote',sd.Remark__c == null ? '' : sd.Remark__c);
            //body.put('ccalbodyid',sn.Contract__r.Vsalestrucode__c);

            bodyList.add(body);

        }


        //组装XML 
        String xml = '<ufinterface roottag="so_preorder" billtype="38" replace="Y" receiver="web" sender="web" isexchange="Y" filename="预订单表头.xml" proc="add" operation="req">';
        xml += '<so_preorder id="'+sn.Id+'" subdoctype="">';
        //组装表头
        xml+='<so_preorder_head>';
        for (String k : headMap.keySet()) {
            xml += '<' +k +'>'+headMap.get(k)+'</'+k+'>';
        }
        xml+='</so_preorder_head>';

        //组装表体
        xml+='<so_preorder_body>';
        for (Map<String,String> row : bodyList) {
            xml+='<entry>';
            for (String k : row.keySet()) {
                xml += '<' +k +'>'+row.get(k)+'</'+k+'>';
            }
            xml+='</entry>';

        }
        xml+='</so_preorder_body>';

        xml +='</so_preorder></ufinterface>';

        System.debug(xml);

        String postURL = Label.queryNCPreOrder;
        ///发送请求
        String data = EncodingUtil.urlEncode(xml,'UTF-8');
        System.debug('*** POST MD5 参数: ' + data); 
        //生成POST请求
        postURL = postURL;
        HttpRequest req = new HttpRequest(); 
        req.setBody('data=' + data+'&account=01&receiver='+companycode);
        req.setEndpoint(postURL); 
        System.debug(req.getBody());
        //POST数据到微信接口，设置编码为GB2312,防止乱码
        req.setHeader('Content-Type','application/x-www-form-urlencoded ; charset=utf-8');
        req.setMethod('POST'); 
        //发送数据并取得返回结果
        HttpResponse res = Utils.postRequest(req,1); 
        //设置编码为GB2312，防止读取数据时乱码
        //res.setHeader('Content-Type','application/x-www-form-urlencoded ; charset=utf-8');
        String result = res.getBody();
        System.debug('*** : ' + result);
        if (res.getStatusCode() == 200) {


             Map<String,Object> r =null;
                 //如果是测试
                if(Test.isRunningTest()){
                  Map<String,Object>  resBody= new Map<String,Object>();
                  resBody.put('code','0');
                  /*
                {"result":"[{\"billpk\":\"\\n        \",\"bdocid\":\"a2A0k0000005HZ3EAM\",\"filename\":\"预订单表头.xml\",\"resultcode\":\"1\",\"resultdescription\":\"单据a2A0k0000005HZ3EAM开始处理...\\n单据a2A0k0000005HZ3EAM处理完毕!\",\"content\":\"业务插件返回值\"}]","code":"0","msg":"success"}
                  */
                  resBody.put('result','[{\"billpk\":\"\\n        \",\"bdocid\":\"a2A0k0000005HZ3EAM\",\"filename\":\"预订单表头.xml\",\"resultcode\":\"1\",\"resultdescription\":\"单据a2A0k0000005HZ3EAM开始处理...\\n单据a2A0k0000005HZ3EAM处理完毕!\",\"content\":\"业务插件返回值\"}]');
                    r =  resBody;
                }else{
                  r= (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
                }

             if(r.get('code') == 0|| r.get('code')=='0' ){
                List<Object> rList = (List<Object> ) JSON.deserializeUntyped(((String)r.get('result')));
                    Map<String,Object> rs = (   Map<String,Object>)rList[0];
                    if(rs.get('resultcode') == 1 || rs.get('resultcode') == '1'){
                       /* for (SameBatchNumber__c sd: sdList) {
                           
                        }*/
                        sn.IsSycToNc__c = true;
                        update sn;
                        //Approval.lock(sn);
                        return '同步成功!';
                    }else{
                        return String.valueOf(rs.get('resultdescription'));
                    }



             }else{

                return '接口异常,请联系系统管理员!';
             }



        }else{

            return '接口异常,请联系系统管理员!';
        }

    }
//备货通知单 推送到NC 为预订单  传入备货通知单的ID
    WebService static String postscargo(Id id) {
       


        List<ScheduledCargo__c> snList = [select Id, IsSycToNc__c ,OwnerCompany__c,Customer__r.AccountNumber,Status__c from ScheduledCargo__c where Id=:id];
        ScheduledCargo__c sn = null;
        if(snList.size() > 0){
            sn = snList[0];
        }else{
            return '预留货物申请单Id错误!';
        }
        if(sn.Status__c != '已批准')return '未审批的备货申请不能同步!';
        if(sn.OwnerCompany__c == null)return '预留货物申请单所属公司必填!';
        if(sn.IsSycToNc__c ==true ) return '已经同步,不要重复点击!';
        Map<String,String >salesMap = getMapfromLabel(Label.Vsalestrucode,true);
        Map<String,String >scomMap = getMapfromLabel(Label.ShortCompanyName,false);
        String scode = salesMap.get(scomMap.get(sn.OwnerCompany__c));
        if(scode == null) return '请联系系统管理员维护销售组织编码!'; 


        Map<String,String> headMap = new Map<String,String>();
        headMap.put('ccurrencytypeid','CNY');
        headMap.put('ccustomerid',sn.Customer__r.AccountNumber);
        headMap.put('creceiptcorpid',sn.Customer__r.AccountNumber);
        headMap.put('creceiptcustomerid',sn.Customer__r.AccountNumber);
        headMap.put('coperatorid',sn.Customer__r.AccountNumber);

        headMap.put('csalecorpid',scode);//销售组织编码
        //headMap.put('csalecorpid','01');
        headMap.put('vnote','预留货物申请');

        headMap.put('fstatus','1');
        headMap.put('creceipttype','38');
        headMap.put('nexchangeotobrate','1.0');
        headMap.put('pk_corp',sn.OwnerCompany__c);//公司
        headMap.put('pk_defdoc6',sn.Customer__r.AccountNumber);
        headMap.put('vdef6',sn.Customer__r.AccountNumber+'-'+sn.Customer__r.AccountNumber);

        headMap.put('dbilldate',Utils.date2string(Date.valueOf(System.now())));
        headMap.put('dabatedate',Utils.date2string(Date.valueOf(System.now().addMonths(2))));


        List<SameBatchNumber__c> sdList = [select Id,Inventory__c,Inventory__r.Unit__c,Inventory__r.NCCode__c,Code__c,CargoDetail__c,Quantity__c,
        SendMount1__c,SendMount2__c,SendMount3__c,SendMount4__c,SendMount5__c,SendMount6__c,SendMount7__c,SendMount8__c,
        SendMount9__c,SendMount10__c,SendMount11__c,SendMount12__c,BatchNumber__c 
        from SameBatchNumber__c where CargoDetail__c =: id ];
        if(sdList.size() == 0)return '没有未同步的备货明细!';
        ///分单
        List<Map<String,String>> bodyList = new List<Map<String,String>>();
        Integer i = 0;
        for (SameBatchNumber__c sd: sdList) {
            i++;
            Map<String,String> body = new Map<String,String>();
            body.put('ccurrencytypeid','CNY' );
            body.put('crowno', String.valueOf(i));
            body.put( 'cinventoryid',sd.Inventory__r.NCCode__c);//存货编码
            body.put('cunitid',sd.Inventory__r.Unit__c);//单位
            body.put('ndiscountrate','100');
            body.put('pk_corp',sn.OwnerCompany__c );//公司编码
            //body.put('nnumber', '2');
            body.put('vdef4', sd.CargoDetail__c);//主表pk
            body.put('vdef3', sd.Id);//子表pk 
            body.put('vdef5', 'SFBH');//子表pk 
            Decimal smounts = 0;
            for (Integer j =1 ;j <= 12 ; j++) {
                if(sd.get('SendMount'+j+'__c') != null){
                    smounts+= Decimal.valueOf(String.valueOf(sd.get('SendMount'+j+'__c')));
                }
            }
            body.put('nnumber', String.valueOf(smounts));//数量


            //body.put('ntaxrate', '17');
            body.put('nmny', '0.01');
            body.put('nprice', '0.01');
            body.put('nnetprice', '0.01');
            body.put('frownote','预留批次'+sd.BatchNumber__c == null ? '' : sd.BatchNumber__c);
            //body.put('ccalbodyid',sn.Contract__r.Vsalestrucode__c);

            bodyList.add(body);

        }


        //组装XML 
        String xml = '<ufinterface roottag="so_preorder" billtype="38" replace="Y" receiver="web" sender="web" isexchange="Y" filename="预订单表头.xml" proc="add" operation="req">';
        xml += '<so_preorder id="'+sn.Id+'" subdoctype="">';
        //组装表头
        xml+='<so_preorder_head>';
        for (String k : headMap.keySet()) {
            xml += '<' +k +'>'+headMap.get(k)+'</'+k+'>';
        }
        xml+='</so_preorder_head>';

        //组装表体
        xml+='<so_preorder_body>';
        for (Map<String,String> row : bodyList) {
            xml+='<entry>';
            for (String k : row.keySet()) {
                xml += '<' +k +'>'+row.get(k)+'</'+k+'>';
            }
            xml+='</entry>';

        }
        xml+='</so_preorder_body>';

        xml +='</so_preorder></ufinterface>';

        System.debug(xml);

        String postURL = Label.queryNCPreOrder;
        ///发送请求
        String data = EncodingUtil.urlEncode(xml,'UTF-8');
        System.debug('*** POST MD5 参数: ' + data); 
        //生成POST请求
        postURL = postURL;
        HttpRequest req = new HttpRequest(); 
        req.setBody('data=' + data+'&account=01&receiver='+sn.OwnerCompany__c);
        req.setEndpoint(postURL); 
        System.debug(req.getBody());
        //POST数据到微信接口，设置编码为GB2312,防止乱码
        req.setHeader('Content-Type','application/x-www-form-urlencoded ; charset=utf-8');
        req.setMethod('POST'); 
        //发送数据并取得返回结果
        HttpResponse res = Utils.postRequest(req,1); 
        //设置编码为GB2312，防止读取数据时乱码
        res.setHeader('Content-Type','application/x-www-form-urlencoded ; charset=utf-8');
        String result = res.getBody();
        System.debug('*** : ' + result);
        if (res.getStatusCode() == 200) {


             Map<String,Object> r =null;
                 //如果是测试
                if(Test.isRunningTest()){
                  Map<String,Object>  resBody= new Map<String,Object>();
                  resBody.put('code','0');
                  /*
                {"result":"[{\"billpk\":\"\\n        \",\"bdocid\":\"a2A0k0000005HZ3EAM\",\"filename\":\"预订单表头.xml\",\"resultcode\":\"1\",\"resultdescription\":\"单据a2A0k0000005HZ3EAM开始处理...\\n单据a2A0k0000005HZ3EAM处理完毕!\",\"content\":\"业务插件返回值\"}]","code":"0","msg":"success"}
                  */
                  resBody.put('result','[{\"billpk\":\"\\n        \",\"bdocid\":\"a2A0k0000005HZ3EAM\",\"filename\":\"预订单表头.xml\",\"resultcode\":\"1\",\"resultdescription\":\"单据a2A0k0000005HZ3EAM开始处理...\\n单据a2A0k0000005HZ3EAM处理完毕!\",\"content\":\"业务插件返回值\"}]');
                    r =  resBody;
                }else{
                  r= (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
                }

             if(r.get('code') == 0|| r.get('code')=='0' ){
                List<Object> rList = (List<Object> ) JSON.deserializeUntyped(((String)r.get('result')));
                    Map<String,Object> rs = (   Map<String,Object>)rList[0];
                    if(rs.get('resultcode') == 1 || rs.get('resultcode') == '1'){
                       /* for (SameBatchNumber__c sd: sdList) {
                           
                        }*/
                        sn.IsSycToNc__c = true;
                        update sn;
                        //Approval.lock(sn);
                        return '同步成功!';
                    }else{
                        return String.valueOf(rs.get('resultdescription'));
                    }



             }else{

                return '接口异常,请联系系统管理员!';
             }



        }else{

            return '接口异常,请联系系统管理员!';
        }





    }



    //自定义对象：申请单-工程配件需求计划 ==> NC 请购单

     WebService static String postRequireBuy(Id id) {
       

        List<EngineeringPartsRequirementPlanning__c> eprpList = [select Id,SyncResult__c, IsSycToNc__c ,Equipment__r.ProductName__c,DemandOrganization__c,Note__c,Company__c,DemandWarehouse__c,Status__c from EngineeringPartsRequirementPlanning__c where Id=:id];
        EngineeringPartsRequirementPlanning__c eprp  = null;
        if(eprpList.size() > 0){
            eprp = eprpList[0];
        }else{
            return '工程配件需求计划申请单Id错误!';
        }
        if(eprp.Status__c != '审批成功')return '未审批的工程配件需求计划申请不能同步!';
        if(eprp.Company__c == null)return '工程配件需求计划申请采购组织必填!';
        if(eprp.DemandWarehouse__c == null)return '工程配件需求计划申请需求仓库必填!';
        if(eprp.DemandOrganization__c == null)return '工程配件需求计划申请需求组织必填!';
        if(eprp.IsSycToNc__c ==true ) return '已经同步,不要重复点击!';
    
        User u = [select Id, ExuserCode__c from User where Id =:UserInfo.getUserId()];


        Map<String,String> headMap = new Map<String,String>();
        headMap.put('caccountyear',String.valueOf(System.now().year()));
        headMap.put('pk_corp',eprp.DemandOrganization__c);
        headMap.put('coperator',u.ExuserCode__c);
        headMap.put('dpraydate',System.now().format('yyyy-MM-dd'));
        headMap.put('vmemo',eprp.Note__c );
        headMap.put('vdef19',eprp.Equipment__r.ProductName__c );
        //headMap.put('vdef20',eprp.Id );



        List<EngineeringPartsRequirementDetails__c> eprdList  = [select Id,NCcode__c,OrderAmount__c
        from EngineeringPartsRequirementDetails__c where EngineeringPartsRequirementPlanning__c =: id ];
        if(eprdList.size() == 0)return '没有未同步的配件明细!';
        ///分单
        List<Map<String,String>> bodyList = new List<Map<String,String>>();
        Integer i = 0;
        for (EngineeringPartsRequirementDetails__c eprd : eprdList) {
            i ++ ;
            Map<String,String> body = new Map<String,String>();
            body.put('rowno', String.valueOf(i));
            body.put( 'cmangid',eprd.NCcode__c);//存货编码
            body.put('npraynum',String.valueOf(eprd.OrderAmount__c));//订货量
            body.put('ddemanddate',System.now().format('yyyy-MM-dd') );
            body.put('pk_corp',eprp.DemandOrganization__c );//公司编码
            body.put('pk_reqcorp',eprp.DemandOrganization__c );//公司编码
            body.put('pk_purcorp',eprp.Company__c );//公司编码 
            body.put('cwarehouseid',eprp.DemandWarehouse__c );//仓库

            bodyList.add(body);

        }


        //组装XML 
        String xml = '<ufinterface roottag="bill" billtype="20" replace="Y" receiver="web" sender="20" isexchange="Y"  proc="add" operation="req">';
        xml += '<bill id="'+eprp.Id+'" subdoctype="">';
        //组装表头
        xml+='<billhead>';
        for (String k : headMap.keySet()) {
            xml += '<' +k +'>'+headMap.get(k)+'</'+k+'>';
        }
        xml+='</billhead>';

        //组装表体
        xml+='<billbody>';
        for (Map<String,String> row : bodyList) {
            xml+='<entry>';
            for (String k : row.keySet()) {
                xml += '<' +k +'>'+row.get(k)+'</'+k+'>';
            }
            xml+='</entry>';

        }
        xml+='</billbody>';

        xml +='</bill></ufinterface>';

        System.debug(xml);

        String postURL = Label.queryNCPreOrder;
       //测试环境地址: 
       // postURL = 'https://esb.maccura.com:9088/api/Domain/even1/ncstock/data';
        ///发送请求
        String data = EncodingUtil.urlEncode(xml,'UTF-8');
        //生成POST请求
        HttpRequest req = new HttpRequest(); 
        // String accountn = 'CS180824' ; // 正式'01'
         String accountn = '01' ; // 正式'01'
        req.setBody('data=' + data+'&account='+accountn+'&receiver='+eprp.DemandOrganization__c);
        req.setEndpoint(postURL); 
        System.debug(req.getBody());
        //POST数据到微信接口，设置编码为GB2312,防止乱码
        req.setHeader('Content-Type','application/x-www-form-urlencoded ; charset=utf-8');
        req.setMethod('POST'); 
        //发送数据并取得返回结果
        HttpResponse res = Utils.postRequest(req,1); 
        //设置编码为GB2312，防止读取数据时乱码
        res.setHeader('Content-Type','application/x-www-form-urlencoded ; charset=utf-8');
        String result = res.getBody();
        System.debug('*** : ' + result);
        if (res.getStatusCode() == 200) {


             Map<String,Object> r =null;
                 //如果是测试
                if(Test.isRunningTest()){
                  Map<String,Object>  resBody= new Map<String,Object>();
                  resBody.put('code','0');
                  /*
                {"result":"[{\"billpk\":\"\\n        \",\"bdocid\":\"a2A0k0000005HZ3EAM\",\"filename\":\"预订单表头.xml\",\"resultcode\":\"1\",\"resultdescription\":\"单据a2A0k0000005HZ3EAM开始处理...\\n单据a2A0k0000005HZ3EAM处理完毕!\",\"content\":\"业务插件返回值\"}]","code":"0","msg":"success"}
                  */
                  resBody.put('result','[{\"billpk\":\"\\n        \",\"bdocid\":\"a2A0k0000005HZ3EAM\",\"filename\":\"预订单表头.xml\",\"resultcode\":\"1\",\"resultdescription\":\"单据a2A0k0000005HZ3EAM开始处理...\\n单据a2A0k0000005HZ3EAM处理完毕!\",\"content\":\"业务插件返回值\"}]');
                    r =  resBody;
                }else{
                  r= (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
                }

             if(r.get('code') == 0|| r.get('code')=='0' ){
                List<Object> rList = (List<Object> ) JSON.deserializeUntyped(((String)r.get('result')));
                    Map<String,Object> rs = (   Map<String,Object>)rList[0];
                    if(rs.get('resultcode') == 1 || rs.get('resultcode') == '1'){
                       /* for (SameBatchNumber__c sd: sdList) {
                           
                        }*/
                        String resJso = JSON.serialize(rs);
                        eprp.SyncResult__c = resJso.length() > 255 ? resJso.substring(0, 254) : resJso;
                        eprp.IsSycToNc__c = true;
                        update eprp;
                        //Approval.lock(sn);
                        return '同步成功!';
                    }else{
                        return String.valueOf(rs.get('resultdescription'));
                    }



             }else{

                return '接口异常,请联系系统管理员!';
             }



        }else{

            return '接口异常,请联系系统管理员!';
        }





    }





    //海外销售订单 推送到NC 为预订单  传入备货通知单的ID
    WebService static String postOverseaOrder(Id id) {
       

        User u = [select Id,ExuserCode__c from User where Id=:UserInfo.getUserId()];

        List<SalesOrderApplication__c> snList = [select Id, IsSycToNc__c,RecordType.DeveloperName ,Buyer__r.AccountNumber,Status__c from SalesOrderApplication__c where Id=:id];
        SalesOrderApplication__c sn = null;
        if(snList.size() > 0){
            sn = snList[0];
        }else{
            return '海外销售订单Id错误!';
        }

        if(sn.Status__c != '已批准')return '未审批的海外销售订单不能同步!';
        if(sn.IsSycToNc__c ==true ) return '已经同步,不要重复点击!';
      
        String scode = sn.RecordType.DeveloperName == 'ReagentSalesOrders' ? '01' : '06';
        String corp = sn.RecordType.DeveloperName ==  'ReagentSalesOrders' ? 'MKSW' : 'MKDZ';

        Map<String,String> headMap = new Map<String,String>();
        headMap.put('ccurrencytypeid','CNY');
        headMap.put('ccustomerid',sn.Buyer__r.AccountNumber);
        headMap.put('creceiptcorpid',sn.Buyer__r.AccountNumber);
        headMap.put('creceiptcustomerid',sn.Buyer__r.AccountNumber);
        headMap.put('coperatorid',u.ExuserCode__c);

        headMap.put('csalecorpid',scode);//销售组织编码
        //headMap.put('csalecorpid','01');
        headMap.put('vnote','SF海外销售订单');

        headMap.put('fstatus','1');
        headMap.put('creceipttype','38');
        headMap.put('nexchangeotobrate','1.0');

        headMap.put('pk_corp',corp);//公司
        headMap.put('pk_defdoc6',sn.Buyer__r.AccountNumber);
        headMap.put('vdef6',sn.Buyer__r.AccountNumber+'-'+sn.Buyer__r.AccountNumber);

        headMap.put('dbilldate',Utils.date2string(Date.valueOf(System.now())));
        headMap.put('dabatedate',Utils.date2string(Date.valueOf(System.now().addMonths(2))));


        List<SalesOrderDetailed__c> sdList = [select Id,Product__c,Product__r.Unit__c,Product__r.NCCode__c,
        No__c,SalesOrderApplication__c
        from SalesOrderDetailed__c where SalesOrderApplication__c =: id ];
        if(sdList.size() == 0)return '没有未同步的海外销售订单明细!';
        ///分单
        List<Map<String,String>> bodyList = new List<Map<String,String>>();
        Integer i = 0;
        for (SalesOrderDetailed__c sd: sdList) {
            i++;
            Map<String,String> body = new Map<String,String>();
            body.put('ccurrencytypeid','USD' );
            body.put('crowno', String.valueOf(i));
            body.put( 'cinventoryid',sd.Product__r.NCCode__c);//存货编码
            body.put('cunitid',sd.Product__r.Unit__c);//单位
            body.put('ndiscountrate','100');
            body.put('pk_corp',corp );//公司编码
            //body.put('nnumber', '2');
            body.put('vdef4', sd.SalesOrderApplication__c);//主表pk
            body.put('vdef3', sd.Id);//子表pk 
            body.put('vdef5', 'SFHWDD');//子表pk 
           
            body.put('nnumber', String.valueOf(sd.No__c));//数量


            //body.put('ntaxrate', '17');
            body.put('nmny', '0.01');
            body.put('nprice', '0.01');
            body.put('nnetprice', '0.01');
            //body.put('frownote','预留批次'+sd.BatchNumber__c == null ? '' : sd.BatchNumber__c);
            //body.put('ccalbodyid',sn.Contract__r.Vsalestrucode__c);

            bodyList.add(body);

        }


        //组装XML 
        String xml = '<ufinterface roottag="so_preorder" billtype="38" replace="Y" receiver="web" sender="web" isexchange="Y" filename="预订单表头.xml" proc="add" operation="req">';
        xml += '<so_preorder id="'+sn.Id+'" subdoctype="">';
        //组装表头
        xml+='<so_preorder_head>';
        for (String k : headMap.keySet()) {
            xml += '<' +k +'>'+headMap.get(k)+'</'+k+'>';
        }
        xml+='</so_preorder_head>';

        //组装表体
        xml+='<so_preorder_body>';
        for (Map<String,String> row : bodyList) {
            xml+='<entry>';
            for (String k : row.keySet()) {
                xml += '<' +k +'>'+row.get(k)+'</'+k+'>';
            }
            xml+='</entry>';

        }
        xml+='</so_preorder_body>';

        xml +='</so_preorder></ufinterface>';

        System.debug(xml);

        String postURL = Label.queryNCPreOrder;
        //postURL = 'https://esb.maccura.com:9088/api/Domain/even1/ncstock/data';
        ///发送请求
        String data = EncodingUtil.urlEncode(xml,'UTF-8');
        System.debug('*** POST MD5 参数: ' + data); 
        //生成POST请求
        postURL = postURL;
        HttpRequest req = new HttpRequest();
                //String accountn = '0001' ; // 正式'01'
 
        req.setBody('data=' + data+'&account=01&receiver='+corp);
        req.setEndpoint(postURL); 
        System.debug(req.getBody());
        //POST数据到微信接口，设置编码为GB2312,防止乱码
        req.setHeader('Content-Type','application/x-www-form-urlencoded ; charset=utf-8');
        req.setMethod('POST'); 
        //发送数据并取得返回结果
        HttpResponse res = Utils.postRequest(req,1); 
        //设置编码为GB2312，防止读取数据时乱码
        res.setHeader('Content-Type','application/x-www-form-urlencoded ; charset=utf-8');
        String result = res.getBody();
        System.debug('*** 微信接口返回结果: ' + result);
        if (res.getStatusCode() == 200) {


             Map<String,Object> r =null;
                 //如果是测试
                if(Test.isRunningTest()){
                  Map<String,Object>  resBody= new Map<String,Object>();
                  resBody.put('code','0');
                  /*
                {"result":"[{\"billpk\":\"\\n        \",\"bdocid\":\"a2A0k0000005HZ3EAM\",\"filename\":\"预订单表头.xml\",\"resultcode\":\"1\",\"resultdescription\":\"单据a2A0k0000005HZ3EAM开始处理...\\n单据a2A0k0000005HZ3EAM处理完毕!\",\"content\":\"业务插件返回值\"}]","code":"0","msg":"success"}
                  */
                  resBody.put('result','[{\"billpk\":\"\\n        \",\"bdocid\":\"a2A0k0000005HZ3EAM\",\"filename\":\"预订单表头.xml\",\"resultcode\":\"1\",\"resultdescription\":\"单据a2A0k0000005HZ3EAM开始处理...\\n单据a2A0k0000005HZ3EAM处理完毕!\",\"content\":\"业务插件返回值\"}]');
                    r =  resBody;
                }else{
                  r= (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
                }

             if(r.get('code') == 0|| r.get('code')=='0' ){
                List<Object> rList = (List<Object> ) JSON.deserializeUntyped(((String)r.get('result')));
                    Map<String,Object> rs = (   Map<String,Object>)rList[0];
                    if(rs.get('resultcode') == 1 || rs.get('resultcode') == '1'){
                       /* for (SameBatchNumber__c sd: sdList) {
                           
                        }*/
                        sn.IsSycToNc__c = true;
                        update sn;
                        //Approval.lock(sn);
                        return '同步成功!';
                    }else{
                        return String.valueOf(rs.get('resultdescription'));
                    }



             }else{

                return '接口异常,请联系系统管理员!';
             }



        }else{

            return '接口异常,请联系系统管理员!';
        }





    }
/*
//备货通知单 推送到NC 为预订单  传入备货通知单的ID
    WebService static String postStock(Id id) {
    	List<StockingNotice__c> snList= [select Id,Contract__c,Contract__r.Corpcode__c,Contract__r.Vsalestrucode__c ,
    	Contract__r.Account__r.AccountNumber ,Contract__r.CompanyControls__c,CreatedDate from StockingNotice__c where Id =:id];
    	StockingNotice__c sn = null;
    	if(snList.size() > 0){
    		sn = snList[0];
    	}else{
    		return '备货通知单Id错误!';
    	}
    	Map<String,String> headMap = new Map<String,String>();
    	headMap.put('ccurrencytypeid','CNY');
    	headMap.put('ccustomerid',sn.Contract__r.Account__r.AccountNumber);
    	headMap.put('creceiptcorpid',sn.Contract__r.Account__r.AccountNumber);
    	headMap.put('creceiptcustomerid',sn.Contract__r.Account__r.AccountNumber);
    	headMap.put('coperatorid',sn.Contract__r.Account__r.AccountNumber);

    	headMap.put('csalecorpid',sn.Contract__r.Vsalestrucode__c);
    	//headMap.put('csalecorpid','01');

    	headMap.put('fstatus','1');
    	headMap.put('creceipttype','38');
    	headMap.put('nexchangeotobrate','1.0');
    	headMap.put('pk_corp',sn.Contract__r.Corpcode__c);
    	headMap.put('pk_defdoc6',sn.Contract__r.Account__r.AccountNumber);
    	headMap.put('vdef6',sn.Contract__r.Account__r.AccountNumber+'-'+sn.Contract__r.Account__r.AccountNumber);

    	headMap.put('dbilldate',Utils.date2string(Date.valueOf(System.now())));
    	headMap.put('dabatedate',Utils.date2string(Date.valueOf(System.now().addMonths(2))));


    	List<StockingDetails__c> sdList = [select Id,StockingProduct__c,Unit__c,Code__c,StockingNotice__c,Quantity__c from StockingDetails__c where StockingNotice__c =: id and IsSycToNc__c != true];
    	if(sdList.size() == 0)return '没有未同步的备货明细!';
    	///分单
    	List<Map<String,String>> bodyList = new List<Map<String,String>>();
    	Integer i = 0;
    	for (StockingDetails__c sd: sdList) {
    		i++;
    		Map<String,String> body = new Map<String,String>();
    		body.put('ccurrencytypeid','CNY' );
    		body.put('crowno', String.valueOf(i));
    		body.put( 'cinventoryid',sd.Code__c);
    		body.put('cunitid',sd.Unit__c);
    		body.put('ndiscountrate','100');
    		body.put('nnumber', String.valueOf(sd.Quantity__c));
    		body.put('pk_corp',sn.Contract__r.Corpcode__c );
    		//body.put('nnumber', '2');
    		body.put('vdef1', sd.StockingNotice__c);//主表pk
    		body.put('vdef3', sd.Id);//子表pk 


    		//body.put('ntaxrate', '17');
    		body.put('nmny', '0');
    		body.put('nprice', '0');
    		body.put('nnetprice', '0');
    		//body.put('ccalbodyid',sn.Contract__r.Vsalestrucode__c);

			bodyList.add(body);

    	}


    	//组装XML 
    	String xml = '<ufinterface roottag="so_preorder" billtype="38" replace="Y" receiver="web" sender="web" isexchange="Y" filename="预订单表头.xml" proc="add" operation="req">';
    	xml += '<so_preorder id="'+sn.Id+'" subdoctype="">';
    	//组装表头
    	xml+='<so_preorder_head>';
    	for (String k : headMap.keySet()) {
    		xml += '<' +k +'>'+headMap.get(k)+'</'+k+'>';
    	}
    	xml+='</so_preorder_head>';

    	//组装表体
    	xml+='<so_preorder_body>';
    	for (Map<String,String> row : bodyList) {
	    	xml+='<entry>';
	    	for (String k : row.keySet()) {
    			xml += '<' +k +'>'+row.get(k)+'</'+k+'>';
	    	}
	    	xml+='</entry>';

    	}
    	xml+='</so_preorder_body>';

    	xml +='</so_preorder></ufinterface>';

    	System.debug(xml);

    	String postURL = 'https://esb.maccura.com:9088/api/Domain/external/ncstock/data';
    	///发送请求
    	String data = EncodingUtil.urlEncode(xml,'UTF-8');
        System.debug('*** POST MD5 参数: ' + data); 
        //生成POST请求
        postURL = postURL;
        HttpRequest req = new HttpRequest(); 
        req.setBody('data=' + data+'&account=01&receiver='+sn.Contract__r.Corpcode__c);
        req.setEndpoint(postURL); 
        //POST数据到微信接口，设置编码为GB2312,防止乱码
        req.setHeader('Content-Type','application/x-www-form-urlencoded ; charset=utf-8');
        req.setMethod('POST'); 
        //发送数据并取得返回结果
        HttpResponse res = Utils.postRequest(req,1); 
        //设置编码为GB2312，防止读取数据时乱码
        res.setHeader('Content-Type','application/x-www-form-urlencoded ; charset=utf-8');
        String result = res.getBody();
        System.debug('*** 微信接口返回结果: ' + result);
        if (res.getStatusCode() == 200) {


        	 Map<String,Object> r =null;
                 //如果是测试
                if(Test.isRunningTest()){
                  Map<String,Object>  resBody= new Map<String,Object>();
                  resBody.put('code','0');
              
                  resBody.put('result','[{\"billpk\":\"\\n        \",\"bdocid\":\"a2A0k0000005HZ3EAM\",\"filename\":\"预订单表头.xml\",\"resultcode\":\"1\",\"resultdescription\":\"单据a2A0k0000005HZ3EAM开始处理...\\n单据a2A0k0000005HZ3EAM处理完毕!\",\"content\":\"业务插件返回值\"}]');
                    r =  resBody;
                }else{
                  r= (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
                }
         	 if(r.get('code') == 0|| r.get('code')=='0' ){
               	List<Object> rList = (List<Object> ) JSON.deserializeUntyped(((String)r.get('result')));
               		Map<String,Object> rs = (	Map<String,Object>)rList[0];
               		if(rs.get('resultcode') == 1 || rs.get('resultcode') == '1'){
    					for (StockingDetails__c sd: sdList) {
    						sd.IsSycToNc__c = true;
    					}
    					update sdList;
    					//Approval.lock(sn);
               			return '同步成功!';
               		}else{
               			return String.valueOf(rs.get('resultdescription'));
               		}



         	 }else{

         	 	return '接口异常,请联系系统管理员!';
         	 }



        }else{

        	return '接口异常,请联系系统管理员!';
        }





    }

*/
    
}